package com.android.takegism.ui;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.takegism.R;
import com.android.takegism.service.ClientService;
import com.android.takegism.utils.Clue;
import com.android.takegism.utils.ClueUtils;
import com.android.takegism.utils.CommandUtils;
import com.android.takegism.utils.MyContext;

public class BeforeUserMainActivity extends AppCompatActivity implements View.OnClickListener {

    public static Handler mainHandler;
    private ImageButton exitBtn;
    private ImageButton lookClues;
    private Button urgentHelp;
    private EditText story_text;
    private ImageView story_img;

    private String cur_plot;
    private int cur_plotImgId;
    private Clue receivedClue = null;

    private ClientService clientService;

    private MediaPlayer mp = null;
    private boolean isRelease = true;

    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_before_user_main);
        init();
    }

    private void init() {
        initMainHandler();

        exitBtn = findViewById(R.id.exit_btn);
        exitBtn.setOnClickListener(this);
        lookClues = findViewById(R.id.look_clues);
        lookClues.setOnClickListener(this);
        urgentHelp = findViewById(R.id.urgentHelp);
        urgentHelp.setOnClickListener(this);
        story_text = findViewById(R.id.story_text);
        story_img = findViewById(R.id.story_img);

        clientService = (ClientService) MyContext.getInstance().getStatics("clientService");


        int Max_Time = 5000;
        countDownTimer = new CountDownTimer(Max_Time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                ;
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onFinish() {
                System.out.println("计时结束");
                mp.stop();
                isRelease = true;
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.exit_btn:
                ExitFun();
                break;
            case R.id.urgentHelp:
                UrgentHelpFun();
//                MusicPlay();
//                countDownTimer.start();
                break;
            case R.id.look_clues:
                startActivity(new Intent(BeforeUserMainActivity.this, MyCluesActivity.class));
                break;
            default:
                break;
        }
    }

    private void UrgentHelpFun() {
        System.out.println("UrgentHelpFun()");
        clientService.sendMsg("#HELP!#");
    }

    private void ExitFun() {
        System.out.println("ExitFun()");
        clientService.disconnect();
        finish();
    }

    private void MusicPlay() {

        if (isRelease) {
            mp = MediaPlayer.create(this, R.raw.case1);
            mp.start();
            isRelease = false;
        } else {
            mp.stop();
            isRelease = true;
        }
    }

    //    @SuppressLint("HandlerLeak")
    public void initMainHandler() {

        mainHandler = new Handler(Looper.myLooper()) {

            @Override
            public void handleMessage(Message msg) {

                // 接收子线程的消息
                switch (msg.what) {
                    case 0x1111://接收服务器admin的数据
                        String tmp_str = msg.obj.toString();
                        System.out.println("----------------接收到服务器发送数据： " + tmp_str);
                        System.out.println("处理数据，正则表达式转换为线索包" +
                                "一定是线索，需要解谜题，解答后会出现新内容、图片");
                        String string = (String) CommandUtils.getInstance().decodeCommand(tmp_str);
                        receivedClue = null;
                        if (string.indexOf("Clue") != -1) {
                            receivedClue = ClueUtils.getInstance().getClues().get(string);
                            System.out.println("线索：" + receivedClue);
                        } else if (string.indexOf("Plot") != -1) {
                            cur_plot = ClueUtils.getInstance().getPlots().get(string);
//                            两种方法合并的
                            cur_plotImgId = ClueUtils.getInstance().getClueString2ImageIdUtils().get(string);

                            if (story_text.getText().toString().equals("")) {
                                story_text.setText(cur_plot + "\t...\n");
                                story_img.setBackground(getDrawable(cur_plotImgId));
//                                story_img.setImageResource(cur_plotImgId);
                            } else {
                                story_text.append(cur_plot + "\t...\n");
                                story_img.setBackground(getDrawable(cur_plotImgId));
                            }

                            System.out.println("剧情:" + cur_plot + "\nimgId:" + cur_plotImgId);
                        }

                        if (receivedClue != null) {
                            //tmp_str新的信息
                            AlertDialog.Builder builder = new AlertDialog.Builder(BeforeUserMainActivity.this);
                            builder.setTitle("触发了新的机关/条件")
                                    .setMessage("解答谜题将获得新的线索，并解锁新剧情\n是否进入?")
                                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(BeforeUserMainActivity.this, UserMainActivity.class);
                                            intent.putExtra("new_clue", receivedClue);
                                            startActivity(intent);
                                        }
                                    })
                                    .setNegativeButton("否", null);
                            builder.create().show();
                        }
                        break;
                    case 0x1114://成功解答谜题，显示新内容
//                        if (cur_plot != null) {
//                            story_text.append(cur_plot);
//                        }
//                        if (cur_plotImgId != 0) {
//                            story_img.setBackground(getDrawable(cur_plotImgId));
////                            story_img.setImageResource(cur_plotImgId);
//                        }
                        System.out.println("新线索");
                        break;
                    case 0x1113://失去连接
                        @SuppressLint("ShowToast") Toast toast = Toast.makeText(BeforeUserMainActivity.this, "失去连接/连接失败！", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        UserMainActivity.showMyToast(toast, 3000);
                        finish();
                        break;
                    default:
                        break;
                }

            }

        };
    }
}